<template>
  <div class="books-container">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline class="search-form">
      <el-form-item label="书名">
        <el-input v-model="searchForm.title" placeholder="请输入书名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 图书卡片网格 ---
    
     功能：以卡片网格形式展示图书（ el-row + el-col 布局），支持搜索、分页、排序
- 特性：
- 搜索表单（ el-form ）支持书名过滤
- 悬停显示借阅按钮（通过 Map 存储悬停状态）
- 分页控件（ el-pagination ）支持每页数量切换
- 用途：图书浏览场景的核心展示组件-->
    <div class="book-grid">
      <el-row :gutter="24">
        <el-col :span="8" v-for="book in bookList" :key="book.id">
          <el-card class="book-card" @mouseenter="() => setHovered(book.id, true)" @mouseleave="() => setHovered(book.id, false)">
            <div class="cover" :style="{ backgroundImage: `url(${book.cover})` }"/>
            <h3 class="book-title">{{ book.title }}</h3>
            <p class="book-author">作者：{{ book.author }}</p>
            <p class="book-info">分类：{{ book.category }}</p>
            <el-button v-show="hovered.get(book.id)" type="primary" size="small" class="borrow-btn">立即借阅</el-button>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页控件 -->
    <el-pagination
      class="pagination"
      :current-page="currentPage"
      @update:current-page="currentPage = $event"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      @update:page-size="pageSize = $event"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getBooks } from '@/services/bookService';

// 搜索表单数据（响应式）
const searchForm = ref({ title: '' });
// 书籍列表数据（响应式）
const bookList = ref([]);
// 分页参数（响应式）
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
// 卡片悬停状态（使用Map存储每个卡片的id对应状态）
const hovered = ref(new Map());

// 排序参数（响应式）
const sortBy = ref('id');
const sortOrder = ref('ascending');

// 悬停状态更新函数
const setHovered = (id, value) => {
  hovered.value.set(id, value);
};

// 数据加载函数
const loadData = async () => {
  try {
    const params = {
      title: searchForm.value.title,
      page: currentPage.value,
      pageSize: pageSize.value,
      sortBy: sortBy.value,
      sortOrder: sortOrder.value
    };
    // 在loadData函数中调用
    const res = await getBooks(params);
    bookList.value = res.data.list;
    total.value = res.data.total;
  } catch (error) {
    console.error('加载书籍数据失败:', error);
  }
};

// 组件挂载后自动加载数据
onMounted(() => {
  loadData();
});

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  loadData();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = { title: '' };
  handleSearch();
};

// 分页切换
const handleCurrentChange = (val) => {
  currentPage.value = val;
  loadData();
};

// 每页数量切换
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  loadData();
};

// 排序变化处理
// 由于原提示指出该函数被定义但未使用，这里推测可能需要在模板中使用该函数，暂时保留函数定义以确保后续可集成
</script>

<style scoped>
.books-container {
  min-height: 100vh;
  padding: 24px;
  background-color: #f8f9fa;
}

.search-form {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  max-width: 1200px;
  margin: 0 auto 32px;
  position: relative;
}

.book-grid {
  flex: 1;
  margin-bottom: 32px;
}

.book-card {
  height: 320px;
  text-align: center;
  padding: 16px;
  transition: transform 0.2s;
  position: relative;
}
.book-card:hover {
  transform: translateY(-4px);
}

.borrow-btn {
  position: absolute;
  bottom: 16px;
  left: 50%;
  transform: translateX(-50%);
  opacity: 0;
  transition: opacity 0.3s ease-in;
}
.book-card:hover .borrow-btn {
  opacity: 1;
}

.cover {
  height: 180px;
  background-size: cover;
  background-position: center;
  border-radius: 4px;
  margin-bottom: 12px;
}

.book-title {
  font-size: 16px;
  color: #2c3e50;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.book-author,
.book-info {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.pagination {
  text-align: center;
  margin-top: 24px;
}
.el-pagination .el-pager li {
  border-radius: 4px;
  margin: 0 4px;
}
.el-pagination .el-pager li.active {
  background-color: #2196F3;
  color: white;
}

@media (max-width: 1024px) {
  .el-col {
    flex: 0 0 50%; /* 对应span=12，占50%宽度 */
    max-width: 50%;
  }
}
@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }
  .sidebar {
    width: 100% !important;
  }
  .el-col {
    flex: 0 0 100%; /* 对应span=24，占100%宽度 */
    max-width: 100%;
  }
  .search-form {
    flex-direction: column;
  }
  .search-btn {
    width: 100%;
  }
}
</style>